const AJAX = getApp().ajax,
  $wx = getApp().$wx,
  getColor = getApp().globalData.getColor;

Page({
  data: {
    getColor: getColor(),
    addressInfo: {},
    isDefaultAddress: false
  },

  onLoad() {
    $wx.setNavColor(getColor().val);
  },

  onShareAppMessage() {

  },

  // 获取手机号
  blurGetPhone(e){
    let phone =  e.detail.value;

    if (phone.length > 0 && !$wx.checkPhone(phone)){
      $wx.showToast('请输入正确的手机号');
    }
  },

  //选择地址
  getAddress() {
    let _this = this;
    wx.chooseLocation({
      success: res => {
        _this.setData({
          addressInfo: res
        });
      }
    })
  },

  // 设置默认地址
  setDefaultAddress() {
    let td = this.data;
    this.setData({
      isDefaultAddress: !td.isDefaultAddress
    });
  },

  //添加收货地址
  formSubmit(e) {
    let form_obj = e.detail.value, td = this.data;

    if (!form_obj.name) {
      $wx.showToast('请输入姓名');
    } else if (!form_obj.gender) {
      $wx.showToast('请选择性别');
    } else if (!form_obj.phone) {
      $wx.showToast('请输入手机号');
    } else if (form_obj.phone.length > 0 && !$wx.checkPhone(form_obj.phone)) {
      $wx.showToast('请输入正确的手机号');
    } else if (!td.addressInfo.name) {
      $wx.showToast('请选择收货地址');
    } else if (!form_obj.door) {
      $wx.showToast('请输入门牌号');
    } else {

      wx.showLoading({
        title: '添加中...',
        mask: true
      });

      AJAX.addAddress({
        name: form_obj.name,
        mobile: form_obj.phone,
        is_default: form_obj.default || '2',
        address: td.addressInfo.name,
        address_detail: td.addressInfo.address,
        sex: form_obj.gender,
        lat: td.addressInfo.latitude,
        lon: td.addressInfo.longitude,
        door: form_obj.door
      },(status, data, msg)=>{
        wx.hideLoading();
        $wx.showToast(msg);

        if(status){
          wx.navigateBack();
        }
      });

    }
  }
});